<template>
  <section class='f-network'>
    <van-nav-bar class="f-nav-bar" title="国内套餐">
      <template #left>
        <van-icon v-if="isBack" name="arrow-left" size="18" @click="pageBack" />

        <div v-else class="f-nav-left" @click="changeMealType(2)">
          <img src="@/assets/icons/home_icon_international.png" alt="">
          <span>国际套餐</span>
        </div>
      </template>
    </van-nav-bar>

    <section class="f-header">
      <p>用户码</p>
      <div class="f-code">
        <van-field class="f-input" v-model="code" placeholder="请输入用户码" clearable type="number" @blur="setCode" />
        <img src="@/assets/icons/btn_arrow_white.png" alt="" @click="openPopupCode()">
      </div>
    </section>

    <section class="f-select-box" v-show="code">
      <ul class="f-tabbar">
        <li v-for="(item,index) in tabbarList" :key="index" :class="{'f-tabbar-s': tabbarS == index}"
          @click="changeTabbar(index,item)">
          <p>{{item.show_name}}</p>
          <p>{{item.show_level_name}}</p>
        </li>
      </ul>

      <p class="f-center" v-if="!tabbarList.length" style="background: #fff;padding-top: 20px;font-size: 12px;">暂无套餐</p>

      <section class="f-meal-box">
        <p class="f-title" v-if="baseList.length">单月套餐</p>
        <ul class="f-meal">
          <li v-for="(item,index) in baseList" :key="index" @click="openPopup(item)">
            <p>{{ item.title }}</p>
            <p>{{ item.price }}元</p>
          </li>
        </ul>

        <p class="f-title" v-if="monthList.length">月固定套餐</p>
        <ul class="f-meal">
          <li v-for="(item,index) in monthList" :key="index" @click="openPopup(item)">
            <p>{{ item.title }}</p>
            <p>{{ item.price }}元</p>
          </li>
        </ul>

        <p class="f-title" v-if="rateList.length">累计套餐</p>
        <ul class="f-meal" style="margin-bottom: 0;">
          <li v-for="(item,index) in rateList" :key="index" @click="openPopup(item)">
            <p>{{ item.title }}</p>
            <p>{{ item.price }}元</p>
          </li>
        </ul>
      </section>
    </section>

    <section class="f-tips" v-show="code && tabbarList.length">
      <p style="font-size: 14px;margin-bottom: 10px;">选购指南</p>
      <p v-html="pack_rule"></p>
    </section>

    <van-popup v-model:show="popup" position="bottom" round class="f-meal-popup" closeable teleport="body">
      <p class="f-title">订购套餐</p>
      <section class="f-card">
        <p>用户码</p>
        <p class="f-mt-10">
          <span>{{code || '--'}}</span>
        </p>
      </section>

      <section class="f-card">
        <p class="f-card-title">
          <span>套餐内容</span>
          <span style="color: #FF3F3F;">¥{{popupForm.price}}</span>
        </p>
        <div class="f-content">
          <p class="p">{{popupForm.title}}</p>
        </div>
      </section>

      <section class="f-card">
        <p class="f-card-title">
          <span>付款方式</span>
        </p>
        <div class="f-content">
          <van-radio-group v-model="payMethod" shape="dot">
            <van-radio name="wxpay" label-position="left" icon-size="16px">
              <div class="f-pay-box">
                <img src="@/assets/icons/withdraw_icon_wx.png" alt="">
                <p>微信支付</p>
              </div>
            </van-radio>
            <van-radio name="alipay" label-position="left" icon-size="16px" style="margin-top: 15px;">
              <div class="f-pay-box">
                <img src="@/assets/icons/withdraw_icon_zfb.png" alt="">
                <p>支付宝支付</p>
              </div>
            </van-radio>
          </van-radio-group>
        </div>
      </section>

      <div class="f-agreement">
        <van-checkbox v-model="agreeCheck" checked-color="#3366FF" icon-size="16px">
          我已阅读并同意
          <span style="color: #3967D9;">《全讯物联充值协议》</span>
        </van-checkbox>
      </div>

      <div class="f-bottom-box">
        <div class="g-flex-ct f-price">
          <p style="color: #0B0000;font-size: 14px;">合计</p>
          <p class="f-ml-10">¥{{popupForm.price}}</p>
        </div>
        <van-button type="primary" round @click="orderSubmit()">
          <p style="padding: 10px 40px">去支付</p>
        </van-button>
      </div>
    </van-popup>

    <van-popup v-model:show="popupCode" position="bottom" round class="f-popup-code" closeable>
      <p class="f-title">选择用户码</p>
      <section class="f-select">
        <p :class="{'f-select-s': selectS == 2}" @click="changeTabbarCode(2)">我的设备用户码</p>
        <p :class="{'f-select-s': selectS == 1}" @click="changeTabbarCode(1)">最近充值用户码</p>
      </section>
      <ul class="f-check-ul">
        <li v-for="(item,index) in codeList" :key="index" @click="selectCode(item)"
          :style="{'color': item == code? '#304EEE': ''}">
          <p>
            <span>{{item}}</span>
            <!-- <span style="font-size: 12px;">（FM_U8）</span> -->
          </p>
          <img v-if="item == code" src="@/assets/icons/icon_tick_selected.png" alt="">
        </li>
        <li v-if="!codeList.length">暂无数据</li>
      </ul>
    </van-popup>
  </section>
</template>
  
<script>
import { ref, reactive, toRefs, onMounted, watch } from 'vue';
import { useRouter, useRoute } from 'vue-router'
import { useStore } from 'vuex';
import api from './api';
import { setStore, getStore, errorDeal } from '@/utils/utils';
import JsBridge from '@/utils/JsBridge.js'

export default {
  emits: ["changeMealType"],

  setup(props, context) {
    const store = useStore()

    const router = useRouter()
    const route = useRoute();

    const state = reactive({
      code: getStore('CURRENT_CODE').code,

      tabbarList: [],
      tabbarS: 0,

      monthList: [],
      baseList: [],
      rateList: [],
      pack_rule: '',

      popup: false,
      popupForm: {},
      payMethod: 'alipay',
      agreeCheck: false,

      popupCode: false,
      selectS: 2,
      codeList: [],
      recentcodeList: [],
      cardsList: [],

      isPack: false,

      isBack: route.query.mealType
    })

    onMounted(() => {
      getCards()

      if (state.code) {
        getProductList()
      }
    })

    const getProductList = () => {
      let json = {
        code: state.code
      }
      api.productList(json).then(res => {
        state.tabbarList = res.data
        if (res.data.length) {
          getListByPack(res.data[0].level_type)
        } else {
          state.pack_rule = ''
          state.baseList = []
          state.monthList = []
          state.rateList = []
        }
      }).catch(err => {
        state.pack_rule = ''
        state.baseList = []
        state.monthList = []
        state.rateList = []
      })
    }

    const getListByPack = (type) => {
      let json = {
        code: state.code,
        type
      }
      api.listByPack(json).then(res => {
        state.pack_rule = res.data.pack_rule
        let pack = res.data.pack
        state.baseList = pack.base ? pack.base : []
        state.monthList = pack.month ? pack.month : []
        state.rateList = pack.rate ? pack.rate : []
      }).catch(err => {
        state.pack_rule = ''
        state.baseList = []
        state.monthList = []
        state.rateList = []
      })
    }

    const changeTabbar = (tabbarS, data) => {
      state.tabbarS = tabbarS
      getListByPack(data.level_type)
    }

    const openPopup = (data) => {
      state.popup = true
      state.popupForm = data
    }

    // 获取最近充值的设备用户码
    const getRecentcode = () => {
      api.recentcode().then(res => {
        let recentcodeList = []
        if (res.data && res.data.length) {
          res.data.forEach(item => {
            recentcodeList.push(item.code)
          })
        }
        state.recentcodeList = recentcodeList
      })
    }

    const getCards = () => {
      api.cards().then(res => {
        let cardsList = []
        if (res.data.devList) {
          res.data.devList.forEach(item => {
            cardsList.push(item.code)
          })
        }
        state.cardsList = cardsList
        changeTabbarCode(2)
      })
    }

    const changeTabbarCode = (selectS) => {
      state.selectS = selectS
      if (selectS == 1) {
        state.codeList = state.recentcodeList
      } else {
        state.codeList = state.cardsList
      }
    }

    const selectCode = (code) => {
      state.code = code
      state.popupCode = false
      setCode()
    }

    // 下单
    const orderSubmit = () => {
      if (!state.agreeCheck) {
        errorDeal("请阅读并同意服务协议")
        return
      }
      let json = {
        code: state.code,
        packId: state.popupForm.pid,
        method: state.payMethod,
        type: 'app', // app调用，sdk：sdk调用
      }
      api.packToPay(json).then(res => {
        // 微信支付
        if (state.payMethod == 'wxpay') {
          JsBridge.callHandler('wxpay', res.data, (res1) => {
            try {
              let data = JSON.parse(res1)
              const { success } = data
              if (success) {
                toOrderDetail(res.data.orderNo)
              } else {
                errorDeal('支付失败！')
              }
            } catch {
              errorDeal('支付失败！')
            }
          })
        }

        // 支付宝支付
        if (state.payMethod == 'alipay') {
          JsBridge.callHandler('alipay', res.data.orderStr, (res1) => {
            try {
              let data = JSON.parse(JSON.parse(res1).msg)
              console.log('alipay', data)
              if (data.alipay_trade_app_pay_response.code == 10000) {
                toOrderDetail(res.data.orderNo)
              } else {
                errorDeal('支付失败！')
              }
            } catch {
              errorDeal('支付失败！')
            }
          })
        }
      })
    }

    const toOrderDetail = (orderno) => {
      router.push({
        path: '/inChina/rechargeRecordDetail',
        query: {
          orderno
        }
      })
    }

    const setCode = () => {
      setStore('CURRENT_CODE', { code: state.code })
      getProductList()
    }

    const changeMealType = (type) => {
      context.emit('changeMealType', type)
    }

    const pageJump = () => {
      router.push({
        path: '/meal/pack'
      })
    }

    const pageBack = () => {
      router.go(-1)
    };

    const openPopupCode = () => {
      state.popupCode = true
      getRecentcode()
    }

    return {
      ...toRefs(state),
      changeTabbar,
      openPopup,
      orderSubmit,
      setCode,
      changeTabbarCode,
      selectCode,
      changeMealType,
      pageJump,
      pageBack,
      openPopupCode
    }
  }
}
</script>
  
<style lang='scss' scoped>
.f-network {
  :deep(.van-cell:after) {
    position: relative;
  }
  :deep(.van-field__control) {
    color: #fff;
  }
  .f-nav-left {
    display: flex;
    align-items: center;
    font-weight: 500;
    font-size: 14px;
    color: #000000;
    img {
      width: 22px;
      height: 22px;
      margin-right: 5px;
    }
  }
  .f-header {
    width: 375px;
    background: #293b63;
    font-weight: 400;
    font-size: 12px;
    color: #ffffff;
    padding: 24px 12px 24px 20px;
    .f-code {
      margin-top: 24px;
      display: flex;
      justify-content: space-between;
      align-items: center;
      .f-input {
        width: 250px;
        background: #293b63;
        padding-left: 0;
        font-size: 18px;
      }
      img {
        width: 7px;
      }
    }
  }
  .f-select-box {
    .f-tabbar {
      width: 375px;
      background: #4869ba;
      font-weight: 300;
      font-size: 12px;
      color: #ffffff;
      display: flex;
      align-items: center;
      justify-content: space-around;
      li {
        text-align: center;
        padding: 12px 0 9px 0;
        border-bottom: 3px solid #4869ba;
        p {
          height: 20px;
        }
      }
      .f-tabbar-s {
        color: #ffc9ab;
        border-bottom: 3px solid #ffc9ab;
      }
    }
    .f-meal-box {
      padding: 27px 0px 27px 7px;
      background: #ffffff;
      .f-title {
        font-weight: 400;
        font-size: 14px;
        color: #000000;
        margin-left: 10px;
      }
      .f-meal {
        display: flex;
        align-items: center;
        flex-wrap: wrap;
        margin: 20px 0 32px 0;
        gap: 20px;
        li {
          width: 104px;
          border-radius: 5px;
          border: 1px solid #aaaaaa;
          font-weight: 400;
          font-size: 14px;
          color: #314fef;
          text-align: center;
          padding: 14px 0;
          p:first-child {
            font-size: 11px;
            color: #0b0000;
            margin-bottom: 10px;
          }
        }
      }
    }
  }
  .f-tips {
    padding: 16px 5px 60px 12px;
    font-weight: 300;
    font-size: 12px;
    color: #0b0000;
    p {
      margin: 10px 0;
      white-space: pre-line;
    }
  }
  .f-popup-code {
    min-height: 400px;
    .f-title {
      font-weight: 500;
      font-size: 16px;
      color: #000000;
      text-align: center;
      padding: 14px 0 0px 0;
    }
    .f-select {
      display: flex;
      align-items: center;
      font-weight: 400;
      font-size: 12px;
      color: #424242;
      justify-content: center;
      margin: 19px 0 30px 0;
      p {
        padding: 7px 12px;
        background: #d9d9d9;
        border: 2px solid #d9d9d9;
      }
      p:first-child {
        border-radius: 3px 0 0 3px;
      }
      p:last-child {
        border-radius: 0 3px 3px 0;
      }
      .f-select-s {
        background: #ffffff;
        color: #3967d9;
      }
    }
    .f-check-ul {
      padding: 0 13px 40px 24px;
      li {
        font-weight: 400;
        font-size: 16px;
        color: #424242;
        display: flex;
        align-items: center;
        justify-content: space-between;
        height: 40px;
        img {
          width: 21px;
          height: 14px;
        }
      }
    }
  }
}
.f-meal-popup {
  .f-title {
    font-weight: 500;
    font-size: 16px;
    color: #000000;
    text-align: center;
    padding: 14px 0 0px 0;
  }
  .f-card {
    width: 347px;
    background: rgba(255, 255, 255, 0.7);
    border-radius: 13px;
    margin: 14px;
    font-weight: 500;
    font-size: 14px;
    color: #0b0000;
    padding: 17px 15px 20px 20px;
    .f-card-title {
      font-weight: 500;
      font-size: 14px;
      color: #0b0000;
      display: flex;
      align-items: center;
      justify-content: space-between;
    }
    .f-content {
      margin-top: 20px;
      font-weight: 400;
      font-size: 12px;
      color: #424242;
      .p {
        height: 20px;
      }
      .f-pay-box {
        display: flex;
        align-items: center;
        font-weight: 400;
        font-size: 14px;
        color: #000000;
        width: 280px;
        img {
          width: 30px;
          height: 30px;
          margin-right: 10px;
        }
      }
    }
  }
  .f-agreement {
    display: flex;
    align-items: center;
    font-weight: 300;
    font-size: 12px;
    color: #424242;
    margin: 12px 24px;
  }
  .f-bottom-box {
    width: 375px;
    background: #ffffff;
    box-shadow: -2px 0px 7px 1px rgba(171, 171, 171, 0.85);
    display: flex;
    align-items: center;
    justify-content: space-between;
    padding: 14px 17px 20px 17px;
    .f-price {
      font-weight: 500;
      font-size: 16px;
      color: #ff3f3f;
    }
  }
}
</style>